using UnityEngine;

namespace ShootingEditor2D
{
    public class Player : MonoBehaviour
    {
        private Rigidbody2D _rigidbody2D;

        private Trigger2DCheck _groundCheck;

        private Gun _gun;

        private void Awake()
        {
            _rigidbody2D = GetComponent<Rigidbody2D>();

            _groundCheck = transform.Find("GroundCheck").GetComponent<Trigger2DCheck>();

            _gun = transform.Find("Gun").GetComponent<Gun>();
        }

        private bool _jumpPressed;
        
        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.K))
            {
                _jumpPressed = true;
            }
            
            if (Input.GetKeyDown(KeyCode.J))
            {
                _gun.Shoot();
            }
        }

        private void FixedUpdate()
        {
            var horizontalMovement = Input.GetAxis("Horizontal");

            _rigidbody2D.velocity = new Vector2(horizontalMovement * 5, _rigidbody2D.velocity.y);

            var grounded = _groundCheck.Triggered;

            if (_jumpPressed && grounded)
            {
                _jumpPressed = false;
                
                _rigidbody2D.velocity = new Vector2(_rigidbody2D.velocity.x, 5);
            }

            _jumpPressed = false;
        }
    }
}
